import 'dart:async';
import 'package:app_links/app_links.dart';
import 'package:sinosheets/utils/common_utils/log_util.dart';

/// URL Scheme 处理器
class UrlSchemeHandler {
  static AppLinks? _appLinks;
  static StreamSubscription<Uri>? _subscription;

  /// 初始化 URL Scheme 处理
  static Future<void> init() async {
    try {
      _appLinks = AppLinks();

      // 获取初始链接（如果应用是通过 URL Scheme 启动的）
      final initialUri = await _appLinks?.getInitialLink();
      if (initialUri != null) {
        handleLink(initialUri);
      }

      // 监听后续的链接
      _subscription = _appLinks?.uriLinkStream.listen((Uri uri) {
        handleLink(uri);
      }, onError: (err) {
        LogUtil.e('URL Scheme 处理错误: $err');
      });
    } catch (e) {
      LogUtil.e('URL Scheme 初始化错误: $e');
    }
  }

  /// 处理接收到的链接
  static void handleLink(Uri uri) {
    if (uri.scheme == 'itaobuy') {
      //替换掉scheme
      String link = uri.toString().replaceFirst('itaobuy://', 'https://');
      //https://?allapp=d00vh40gpf6jq00g549g&allapp_ssid=246381062715793408&utm_source=&redirect_url=https%3A%2F%2Fwww.xbuy.tech%2Fproduct-detail%3Furl%3Dhttps%253A%252F%252Fweidian.com%252Fitem.html%253FitemID%253D7357646699%2526spider_token%253D4572%26inviteCode%3D123456&url=https%3A%2F%2Fweidian.com%2Fitem.html%3FitemID%3D7357646699%26spider_token%3D4572&inviteCode=123456&tl_store=google
      //判断是都是上面的这种链接 解析出redirect_url
      if (link.contains('redirect_url=')) {
        String redirectUrl = link.split('redirect_url=')[1].split('&')[0];
        LogUtil.e('redirectUrl: $redirectUrl');
        //decode
        redirectUrl = Uri.decodeComponent(redirectUrl);
        // LinkCheck.handleLink(redirectUrl);
      } else {
        // LinkCheck.handleLink(link);
      }
    }
  }

  /// 释放资源
  static void dispose() {
    _subscription?.cancel();
    _subscription = null;
    _appLinks = null;
  }
}
